package mspdt.ubzuuch.mn;

import java.text.NumberFormat;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ItemActivity extends Activity{
	
	private ListView listView;
	ListAdapter list_adapter;
	ArrayList<String> names = new ArrayList<String>();
	ArrayList<String> descriptions = new ArrayList<String>();
	ArrayList<String> prices = new ArrayList<String>();
	ArrayList<String> ids = new ArrayList<String>();
	ArrayList<String> images = new ArrayList<String>();
	private String url = "";
	private int tv_id = 0;
	static Activity ia;
	private boolean fromDB = false;
	private NetworkConnectionClass network;
	private boolean scrollable = false;
	private int page = 1;
	private ProgressBar progress;
  	@Override
	public void onBackPressed() {
	   finish();
	   overridePendingTransition(R.anim.left_in, R.anim.right_out);
	}
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.item_body);
		network=new NetworkConnectionClass(this);
		ia=this;
		progress=(ProgressBar)findViewById(R.id.item_body_progress);
		progress.setVisibility(View.GONE);
		Bundle bundle = getIntent().getExtras();
		tv_id = bundle.getInt("title");
		url = bundle.getString("URL");
		listView=(ListView)findViewById(R.id.item_list);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				Intent intent = null;
				if(tv_id==R.id.title_menu_4)
					intent = new Intent(ItemActivity.this, UBViewActivity.class);
				else if(tv_id==R.id.title_menu_5)
					intent = new Intent(ItemActivity.this, ViewActivity.class);
				else
					intent = new Intent(ItemActivity.this, ViewActivity.class);
					
				
				Bundle bundle = new Bundle();
				bundle.putInt("title", tv_id);
				bundle.putString("id", ids.get(arg2));
				bundle.putBoolean("isfromdb", fromDB);
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.right_in, R.anim.left_out);
			}
		});
		listView.setOnScrollListener(new OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

		            final int lastItem = firstVisibleItem + visibleItemCount;
		            if(lastItem == totalItemCount) {
		                // Last item is fully visible.
		            	if(scrollable)
		            	{
		            		progress.setVisibility(View.VISIBLE);
		            		scrollable=false;
		            		loadPageData(page);
		            	}
		            	else
		            	{
		            		
		            	}
		            	
		            }
			}
		});
		
		createTitleComponents();
		findViewById(tv_id).setBackgroundResource(R.drawable.text_background);
		createExpData();
	}
	public void loadPageData(int page_number)
	{
		url=url.replace("page="+(page-1), "page="+page);
    	
    			final Handler handler = new Handler() {
    			   public void handleMessage(Message msg) {
    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
    				   if(msg.what==1)
    				   {
    					   list_adapter.notifyDataSetChanged();
        				  //list_adapter=new ListAdapter(ItemActivity.this, names, descriptions, prices, images);
        				   //listView.setAdapter(list_adapter);
    				   }
    				   else
    					   Toast.makeText(ItemActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
    				   progress.setVisibility(View.GONE);
    			      }
    			   };
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   if(network.isConnectedToServer(url.replace(" ", "%20"), 5000) && network.isNetworkConnected())
    				   {
    					   JSONfuncObject json_func = new JSONfuncObject();
        				   JSONObject json_data = json_func.getJSONfromURL(url.replace(" ", "%20"));
        				   
        				   try {
    						JSONArray name_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_title));
    						JSONArray id_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_id));
    						JSONArray body_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_body));
    						JSONArray price_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_price));
    						JSONArray image_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_image));
    						if(name_array.length()==10)
    						{
    							page+=1;
    							scrollable=true;
    						}
    						else
    						{
    							scrollable=false;
    						}
    							
    							
    						for(int i=0;i<name_array.length();i++)
    						{
    							names.add(name_array.getString(i));
    							descriptions.add(body_array.getString(i));
    							ids.add(id_array.getString(i));
    							prices.add(NumberFormat.getIntegerInstance().format(Long.parseLong(price_array.getString(i))));
    							
    							images.add(ItemActivity.this.getResources().getString(R.string.url_room_image)+image_array.getString(i).split(",")[0]);
    						}
    					} catch (NotFoundException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					} catch (JSONException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
        				   handler.sendEmptyMessage(1);
    				   }
    				   else
    					   handler.sendEmptyMessage(0);
    				   
    			      }
    			   };
    			checkUpdate.start();
	}
	public void createExpData()
	{
		//JSON уншаагүй байгаа болохоор тест маягаар гараас шууд өгөгдөл уншиж байгаа Json уншихад Thread доторхыг солино
		names.clear();
		descriptions.clear();
		prices.clear();
		ids.clear();
		final ProgressDialog dialog = ProgressDialog.show(ItemActivity.this, null, 
    			getResources().getString(R.string.dialog_please_wait), true);
    	
    			final Handler handler = new Handler() {
    			   public void handleMessage(Message msg) {
    				   //RUN доторх үйлдэл хийгдэж дуусахад уншсан мэдээллүүдээ adapter-т хийж өгнө
    				   if(msg.what==1)
    				   {
    					   if(names.size()<10)
    						   scrollable=false;
        				   list_adapter=new ListAdapter(ItemActivity.this, names, descriptions, prices, images);
        				   listView.setAdapter(list_adapter);
    				   }
    				   else
    				   {
    					   Toast.makeText(ItemActivity.this, "Сервэртэй холбогдоход алдаа гарлаа", 3000).show();
    					   finish();
    				   }
    					   

    				   dialog.dismiss();
    			      }
    			   };
    			Thread checkUpdate = new Thread() {  
    			   public void run() {
    				   //энэ дотор Json-с дата уншиж харгалзах утгуудад нь хийж өгнө
    				   if(network.isConnectedToServer(url.replace(" ", "%20"), 5000) && network.isNetworkConnected())
    				   {
    					   Log.d("TEST", "url="+url);
    					   JSONfuncObject json_func = new JSONfuncObject();
        				   JSONObject json_data = json_func.getJSONfromURL(url.replace(" ", "%20"));
        				   Log.d("TEST", "json="+json_data);
        				   try {
    						JSONArray name_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_title));
    						JSONArray id_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_id));
    						JSONArray body_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_body));
    						JSONArray price_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_price));
    						JSONArray image_array = json_data.getJSONArray(ItemActivity.this.getResources().getString(R.string.json_item_get_image));
    						if(name_array.length()==10)
    						{
    							page+=1;
    							scrollable=true;
    						}
    						else
    						{
    							scrollable=false;
    						}
    						for(int i=0;i<name_array.length();i++)
    						{
    							names.add(name_array.getString(i));
    							descriptions.add(body_array.getString(i));
    							ids.add(id_array.getString(i));
    							if(!price_array.getString(i).equals(""))
    								prices.add(NumberFormat.getIntegerInstance().format(Long.parseLong(price_array.getString(i))));
    							else
    								prices.add("???");
    							images.add(ItemActivity.this.getResources().getString(R.string.url_room_image)+image_array.getString(i).split(",")[0]);
    						}
    					} catch (NotFoundException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					} catch (JSONException e) {
    						// TODO Auto-generated catch block
    						e.printStackTrace();
    					}
        				   handler.sendEmptyMessage(1);
    				   }
    				   else
    					   handler.sendEmptyMessage(0);
    				   
    			      }
    			   };
    			checkUpdate.start();
    			
		
	}
	
	public void createTitleComponents()
	{
		//Хуудасны дээр байрлах толгой хэсгийн хийх үйлдлүүд
		
		//Үндсэн товчлууруудын үйлдэл
		//Буцах товчлуур
		findViewById(R.id.back).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		//Хадгалсан мэдээ унших товчлуур
		findViewById(R.id.title_history).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(ItemActivity.this, ItemActivityFromDB.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Хайх товчлуур
		findViewById(R.id.title_search).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(ItemActivity.this, SearchActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Тухай товчлуур
		findViewById(R.id.title_info).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				startActivity(new Intent(ItemActivity.this, InformationActivity.class));
				overridePendingTransition(R.anim.top_in, R.anim.no_anim);
			}
		});
		//Home буюу лого дээр дарах үйлдэл
		findViewById(R.id.home).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
			}
		});
		
		
		
		//Програмын үндсэн менюны үйлдлүүд
		findViewById(R.id.title_menu_1).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ItemActivity.this, MainActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_2).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ItemActivity.this, RentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_3).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ItemActivity.this, NewApartmentActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_4).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ItemActivity.this, UBActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
		findViewById(R.id.title_menu_5).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(ItemActivity.this, AutomobileActivity.class); 
				intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK); 
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.left_in, R.anim.right_out);
			}
		});
	}
}
